import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI } from '@/api/user'

const state = {
  token: getToken() || ''
}
const mutations = {
  // 设置token
  setToken: (state, token) => {
    state.token = token
    setToken(token)
  },
  // 删除token
  removeToken: (state) => {
    state.token = ''
    removeToken(setToken)
  }
}
const actions = {
  // 登录
  async login(context, { username, password }) {
    // 1. 发送登录请求
    // 2. 获取token
    const { data } = await loginAPI({ username, password })
    console.log(data)

    // 3. 提交mutation'
    context.commit('setToken', data.token)
    // 提示用户
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
